<template>
	<new-table v-bind="state" @handleSizeChange="onHandleSizeChange" @handleCurrentChange="onHandleCurrentChange"
		@handleEdit="onHandleEdit" @handleDelete="onHandleDelete" :row-style="rowStyle">
		<template #search>
			<new-form :formOptions="formOptions" :searchForm="searchForm" @search="onSearch" />
		</template>

		<template #btn>
			<el-button type="primary" @click="gotoRecordOrder">
				+ 录单
			</el-button>
		</template>
	</new-table>
	<EditOrder ref="editOrderRef" :orderData="currentOrderData" :handleType="HandleType.EIDT"
		@handleUpdated="onHandleUpdated" />
</template>

<script setup lang="ts" name="FormTableDemoExample">
import { onMounted, reactive, toRefs, ref, watchEffect } from "vue";
import { HooksReturnDataType, RelationList, OrderStateList, StateList, HandleType, FormatCourseidsAndCityids } from '../const';
import { getClueSearch, getClueDel, getClueGet } from "../api";
import EditOrder from './components/EditOrder.vue'
import NewTable from 'src/components/NewTable/index.vue'
import NewForm from 'src/components/NewForm/index.vue'
import { useSourceList, useCourseList, useJigouList, useCityList, useUserList, useValidateDepartmentList } from "src/hooks";
import utils from "src/utils";
import { useRouter } from "vue-router";

const today = utils.getTodayDate()
const router = useRouter()
const editOrderRef = ref<InstanceType<typeof EditOrder> | null>(null);
const currentOrderData = reactive<any>({})
const renderCB = (groups: any[], value: any, key_val = 'value', key_key = 'label'): any => {
	return (groups.filter(group => `${group[key_val]}` === `${value}`)[0] || {})[key_key]
}
const [SourseList] = useSourceList();
const [CourseList] = useCourseList();
const [JigouList] = useJigouList(null, HooksReturnDataType.SELECT);
const [CityList] = useCityList();

const [userList] = useUserList();
const [validateDepartmentList] = useValidateDepartmentList();

const state = reactive({
	/**
	 * 	"adddate": "添加日期",
		"addtime": "添加时间",
		"agencyName": "经销商名称",
		"agencyid": "经销商id",
		"cityName": "城市名称",
		"cityid": "城市id",
		"contactType": "联系类型1-手机号，2-微信",
		"courseName": "一级类目名称",
		"courseName2": "二级类目名称",
		"courseName3": "课程名称",
		"courseid": "一级类目id",
		"courseid2": "二级类目id",
		"courseid3": "课程id",
		"departmentName": "部门名称",
		"departmentid": "部门id",
		"effective": "0-有效，1-被冲单",
		"id": "线索id",
		"jiGouVOList": "机构",
		"mobile": "手机号",
		"online": "1-线上，2-线下",
		"qq": "qq号",
		"sourceName": "来源名称",
		"sourceid": "来源id",
		"status": "1-未处理，2-已成交，3-用户退款，4-删除",
		"studentName": "学员名称",
		"tips": "备注",
		"userName": "录入人姓名",
		"userid": "录入人id",
		"wechat": "微信号"
	 */
	tableHeader: <TableHeader[]>[
		{ label: "推广员", prop: "userName", width: 80 },
		{ label: "学员", prop: "studentName", width: 100 },
		{
			label: "手机/微信", prop: "wechat", width: 200, render: (value: any, row: Api_ClueManager.ClueItemType) => {
				if (`${row.contactType}` === '1') {
					return row.mobile
				} else {
					return row.wechat
				}
			}
		},
		{
			label: "意向城市", prop: "city", width: 120, render: (value: any) => {
				if (!value || !value.label) return ''
				return `${value.label}/${value.children[0].label}`
			}
		},
		{
			label: "意向课程", prop: "courseName", width: 280, render: (value: any, row: Api_ClueManager.ClueItemType) => {
				return `${value}/${row.courseName2}/${row.courseName3}`
			}
		},
		{ label: "来源", prop: "sourceName" },
		{ label: "订单时间", prop: "addtime", width: 200 },
		{ label: "冲单", prop: "effective", render: (value: any) => renderCB(OrderStateList, value) },
		{ label: "线索状态", prop: "status", render: (value: any) => renderCB(StateList, value) },
		{
			label: "操作",
			fixed: "right",
			slotKey: "default",
			width: 120,
		},
	],
	//表项数据
	tableData: <Api_ClueManager.ClueItemType[]>[],
	formOptions: <FormOptions[]>[],
	//这里允许动态属性所以可为空
	searchForm: <SearchFormType>{},
	isShowSearchRegion: true,
	isShowBtnRegion: true,
	showOverflowTooltip: true,
	pageNum: 1,
	pageSize: 10,
	total: 0,
	tableHeight: "calc(100vh - 302px)",
	isIndex: false
});
const { formOptions, searchForm, pageNum, pageSize } = toRefs(state);
const gotoRecordOrder = () => {
	router.push('/clue')
}
// 修改
const onHandleEdit = (row: any) => {
	currentOrderData.value = { ...row }
	editOrderRef.value?.openDialog();
	// getClueGet({id: row.id}).then((res) => {
	// 	console.log('🤺🤺 表项 🚀  getClueGet==>:', res);
	// });
};
const onHandleUpdated = () => {
	editOrderRef.value?.closeDialog();
	getTableList();
}
const _getClueDel = (id: number | string) => {
	getClueDel({ id }).then((res) => {
		utils.commonNotification({
			condition: `${res.code}` === '0',
			msg_success: '删除成功',
			callback_success: () => getTableList()
		})
	});
}

// 删除
const onHandleDelete = (row: any) => {
	_getClueDel(row.id)
};
const rowStyle = (row: { row: Api_ClueManager.ClueItemType }) => {
	const style: any = {}
	if (`${row.row.effective}` === '1') {
		style.color = '#dd4b39'
	}
	return style
}

//页容量改变
const onHandleSizeChange = (val: number) => {
	// console.log('页容量 ==>：', val);
	pageSize.value = val;
	getTableList();
};
//当前分页改变
const onHandleCurrentChange = (val: number) => {
	// console.log('当前页 🚀 ==>：', val);
	pageNum.value = val;
	getTableList();
};

// 获取表项数据
const getTableList = () => {
	let params = utils.cloneDeep(searchForm.value)
	if (params.searchTime) {
		params.search_b_time = params.searchTime[0] + ' 00:00:00';
		params.search_e_time = params.searchTime[1] + ' 00:00:00';
	}
	delete params.searchTime;
	FormatCourseidsAndCityids(params)
	getClueSearch({
		page: pageNum.value,
		size: pageSize.value,
		order: 'desc',
		columnName: 'addtime',
		...params
	}).then((res) => {
		if (`${res.code}` === '0') {
			const { total, clueVOList } = res.data;
			state.total = total;
			state.tableData = [...clueVOList]
		} else {
			state.total = 0;
			state.tableData = []
		}
	});
};

const onSearch = (isReset?: string) => {
	pageNum.value = isReset ? 1 : pageNum.value;
	getTableList();
};

watchEffect(() => {
	state.formOptions = [
		{
			type: "select",
			props: {
				label: "部门",
				placeholder: "请选择部门",
				clearable: true,
			},
			vm: "departmentid",
			selectOptions: [...validateDepartmentList]
		},
		{
			type: "select",
			props: {
				label: "推广员",
				placeholder: "请选择推广员",
				clearable: true,
			},
			vm: "userid",
			selectOptions: [...userList]
		},
		{
			type: "select",
			props: {
				label: "机构",
				placeholder: "请选择机构",
				clearable: true,
			},
			vm: "jigouid",
			selectOptions: [...JigouList]
		},
		{
			type: "cascader",
			props: {
				label: "意向城市",
				placeholder: "请选择意向城市",
				clearable: true,
				value: 'id',
				filterable: true
			},
			vm: "cityid",
			cascaderOptions: [...CityList]
		},
		{
			type: "cascader",
			props: {
				label: "意向课程",
				placeholder: "请选择意向课程",
				clearable: true,
				value: 'id',
				filterable: true
			},
			vm: "courseid",
			cascaderOptions: [...CourseList]
		},
		{
			type: "select",
			props: {
				label: "状态",
				placeholder: "请选择状态",
				clearable: true,
			},
			vm: "status",
			selectOptions: [...StateList]
		},
		{
			type: "select",
			props: {
				label: "冲单状态",
				placeholder: "请选择冲单状态",
				clearable: true,
			},
			vm: "effective",
			selectOptions: [...OrderStateList]
		},
		{
			type: "select",
			props: {
				label: "联系方式",
				placeholder: "请选择联系方式",
				clearable: true,
			},
			vm: "contactType",
			selectOptions: [...RelationList]
		},
		{
			type: "select",
			props: {
				label: "来源",
				placeholder: "请选择来源",
				clearable: true,
				filterable: true
			},
			vm: "sourceid",
			selectOptions: [...SourseList]
		},
		{
			type: "input",
			props: {
				label: "搜索",
				placeholder: "请输入手机号/微信号",
				clearable: true,
			},
			vm: "contact",
		},
		// 时间范围选择器
		{
			type: "date-picker",
			props: {
				label: "录入时间",
				type: "daterange", // daterange范围 datetime日期
				clearable: true,
				"range-separator": "-",
				"start-placeholder": "开始日期",
				"end-placeholder": "结束日期",
				"value-format": "YYYY-MM-DD",
				format: "YYYY-MM-DD",
			},
			vm: "searchTime",
		},
	]
})

onMounted(async () => {
	state.searchForm.searchTime = [today, today]
	getTableList()
	// const res1 = await getClueGet()
	// console.log('res111 ==== onmounted ', res1);
});
</script>
